package com.xuyaxu.rabbitmq.direct;

import com.rabbitmq.client.*;
import com.xuyaxu.rabbitmq.common.utils.RabbitmqUtil;

import java.io.IOException;

/**
 * direct消息模型（消费者）routingkey为select
 *
 * @author xyx
 * @date 2021/3/30 9:52
 */
public class DirectRecv2 {

    /**
     * 队列名称
     */
    private static final String QUEUE_NAME = "direct_exchange_queue_2";

    public static void main(String[] args) throws Exception {
        // 获取到连接
        Connection connection = RabbitmqUtil.getConnection();
        // 获取通道
        Channel channel = connection.createChannel();
        // 声明exchange，指定类型为direct
        channel.exchangeDeclare("direct_exchange_test", "direct");
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 绑定队列到交换机，同时指定需要订阅的routing key
        channel.queueBind(QUEUE_NAME, "direct_exchange_test", "select");

        // 定义队列的消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                // body 即消息体
                String msg = new String(body);
                System.out.println(" [direct]商品【查询】  " + msg + "!");
            }
        };
        // 监听队列，自动ACK
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }


}
